package com.iot08.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.common.constant.ConstKafka;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.common.utils.response.ResponseMap;
import com.iot08.api.vo.request.ImeiAndIdsParamReqVO;
import com.iot08.api.vo.request.ImeiParamReqVO;
import com.iot08.common.config.mongodb.query.UpdateVO;
import com.iot08.common.service.base.BaseService;
import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.PpChatGroup;
import com.iot08.common.utils.CollectionUtil;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2020/12/1 14:54
 */
@Slf4j
@Service
public class PpChatGroupService extends BaseService<PpChatGroup> {

    @Resource
    private DeviceService deviceService;
    @Resource
    private BaseBucketTool baseBucketTool;

    /**
     * @param imei
     * @time: 2020/12/1 16:19
     * @author: Rock
     * @version 1.0
     */
    public PpChatGroup getByImei(String imei) {
        return this.findOne(new Query(Criteria.where("imei").is(imei)));
    }

    /**
     * 获取好友列表
     *
     * @param chatGroup
     * @time: 2020/12/17 16:10
     * @author: Rock
     * @version 1.0
     */
    public List<JSONObject> getFriends(PpChatGroup chatGroup) {

        List<JSONObject> data = new ArrayList<>();
        if (chatGroup != null && CollectionUtil.isNotEmpty(chatGroup.getMemberMap())) {
            Device mainDev = deviceService.findById(chatGroup.getImei());
            for (Map.Entry<String, Map<String, Object>> entry : chatGroup.getMemberMap().entrySet()) {
                Device device = deviceService.findById(entry.getKey());
                if (device == null) {
                    log.error("Device is null. id={}. getFriends", entry.getKey());
                    continue;
                }

                JSONObject temp = new JSONObject();
                temp.put("imei", entry.getKey());
                if (StringUtil.isNotBlank(entry.getValue().get("time"))) {
                    temp.put("time", new Double(entry.getValue().get("time").toString()).longValue());
                } else {
                    temp.put("time", DateUtil.nowTimestampToDouble().longValue());
                }
                temp.put("phone", StringUtil.isBlank(device.getPhone()) ? "" : device.getPhone());
                temp.put("image", baseBucketTool.getDOMAIN() + BaseBucketTool.DEVICE_COMMON_PATH
                        + (StringUtil.isBlank(device.getImage()) ? Const.DEFAULT_JPG : device.getImage()));
                if (StringUtil.isBlank(device.getName()) && entry.getKey().length() > 4) {
                    temp.put("name", entry.getKey().substring(entry.getKey().length() - 4));
                } else {
                    temp.put("name", device.getName());
                }
                try {
                    //先判断是否 有同样的视频厂商
                    String tempVideoModules = device.getModules();
                    String mainVideoModules = mainDev.getModules();
                    if(tempVideoModules != null && mainVideoModules != null){
                        String[] tempV0 = tempVideoModules.split("V0");
                        String[] mainV0 = mainVideoModules.split("V0");
                        if(tempV0.length == mainV0.length && tempV0.length > 1){
                            //确保2个都有视频
                            String tempV = tempV0[tempV0.length - 1];
                            String mainV = mainV0[mainV0.length - 1];
                            if(tempV.equals(mainV)){
                                if(mainDev.getWatchCustomFunction() != null &&
                                        mainDev.getWatchCustomFunction().contains("DTOD_VIDEO") &&
                                        device.getWatchCustomFunction() != null &&
                                        device.getWatchCustomFunction().contains("DTOD_VIDEO")
                                ){
                                    temp.put("canVideo", 1);
                                }
                            }

                        }
                    }

                    data.add(temp);
                }catch (Exception error){
                    log.error("碰碰交友,判断双方 视频厂商时出错,error:"+error.getMessage(),error);
                    data.add(temp);
                }

            }
        }
        return data;
    }

    /**
     * 查询设备的 好友列表
     *
     * @param vo
     * @time: 2020/12/17 15:28
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap listFriends(ImeiParamReqVO vo) {
        PpChatGroup chatGroup = getByImei(vo.getImei());
        ResponseMap res = ResponseMap.success();
        res.put("friends", this.getFriends(chatGroup));
        return res;
    }

    /**
     * 删除设备的好友
     *
     * @param vo
     * @time: 2020/12/17 17:25
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap delFriends(ImeiAndIdsParamReqVO vo) {
        PpChatGroup chatGroup = getByImei(vo.getImei());
        JSONArray idArr = JSON.parseArray(vo.getIds());
        for (int i = 0; i < idArr.size(); i++) {
            String id = idArr.getString(i);
            //删除
            CollectionUtil.removeMapKey(chatGroup.getMemberMap(), id);
            PpChatGroup cg = getByImei(id);
            if (cg != null) {
                CollectionUtil.removeMapKey(cg.getMemberMap(), vo.getImei());
                //删除更新
                UpdateVO updateSub = new UpdateVO();
                updateSub.setMap("m", cg.getMemberMap());
                this.updateById(new ObjectId(cg.getId()), updateSub);
//                //下发同步好友 指令
//                JSONObject json = new JSONObject();
//                json.put("syncfriends", getFriends(cg));
//                kafkaService.emitDeviceDemand(id, ConstKafka.DEVICE_TYPE_72, json);
            }
        }
        UpdateVO update = new UpdateVO();
        update.setMap("m", chatGroup.getMemberMap());
        this.updateById(new ObjectId(chatGroup.getId()), update);
//        //下发同步好友 指令
//        JSONObject json = new JSONObject();
//        json.put("syncfriends", getFriends(chatGroup));
//        kafkaService.emitDeviceDemand(vo.getImei(), ConstKafka.DEVICE_TYPE_72, json);
        return ResponseMap.success();
    }

    /**
     * @param ppChatGroup
     * @param imei
     * @time: 2021/1/11 11:05
     * @author: Rock
     * @version 1.0
     */
    public void addMember(PpChatGroup ppChatGroup, String imei) {
        if (ppChatGroup.getMemberMap() == null) {
            ppChatGroup.setMemberMap(new HashMap<>());
        }
        Map<String, Object> temp = new HashMap<>();
        temp.put("time", DateUtil.nowTimestampToLong());
        ppChatGroup.getMemberMap().put(imei, temp);
        Update update = new Update();
        update.set("m", ppChatGroup.getMemberMap());
        this.updateById(new ObjectId(ppChatGroup.getId()), update);
    }

    /**
     * @param imei
     * @param otherimei
     * @time: 2021/1/26 11:50
     * @author: Rock
     * @version 1.0
     */
    public PpChatGroup add(String imei, String otherimei) {
        PpChatGroup ppChatGroup = new PpChatGroup();
        ppChatGroup.setImei(imei);
        ppChatGroup.setTime(DateUtil.nowTimestampToDouble());
        ppChatGroup.setMemberMap(new HashMap<>());
        if (StringUtil.isNotBlank(otherimei)) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("time", DateUtil.nowTimestampToLong());
            ppChatGroup.getMemberMap().put(otherimei, temp);
        }
        return this.save(ppChatGroup);
    }
}
